package com.region.common.adapter.json;

import com.region.common.adapter.json.convert.JsonConvertor;
import com.region.common.adapter.json.fastjson.FastjsonAdapter;
import com.region.common.adapter.json.fastjson2.Fastjson2Adapter;
import com.region.common.adapter.json.gson.GsonAdapter;
import com.region.common.adapter.json.jackson.JacksonAdapter;
import com.region.common.utils.ClassUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * The Json Adapter Factory
 *
 * @author liujieyu
 * @date 2023/5/28 14:10
 * @desciption
 */
public class JSONAdapterFactory {

    private static JSONAdapter adapter = null;

    private static List<JsonConvertor> convertors = new LinkedList<>();

    static {
        try {
            tryUseAdapter(Fastjson2Adapter.class);
            tryUseAdapter(JacksonAdapter.class);
            tryUseAdapter(GsonAdapter.class);
            tryUseAdapter(FastjsonAdapter.class);
        } catch (Throwable t) {
            // auto adapter json framework, no need to output error logs
        }
    }

    private static void tryUseAdapter(Class<? extends JSONAdapter> clazz) {
        if (adapter == null) {
            useAdapter(clazz);
        }
    }

    public static void useAdapter(Class<? extends JSONAdapter> clazz) {
        adapter = ClassUtils.newInstance(clazz);
    }

    public static void addConvert(JsonConvertor convertor) {
        convertors.add(convertor);
    }

    public static JSONAdapter getAdapter() {
        return adapter;
    }

    public static List<JsonConvertor> getConvertors() {
        return convertors;
    }
}
